﻿using System;
using System.Collections.Generic;
using Common;
using System.Web.Script.Serialization;
using Educational.Business;
using Basic.Business;
using Educational.VO;

public partial class Educational_Ajax_SchoolManage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //强制刷新页面
        Response.Buffer = true;
        Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
        Response.Expires = 0;
        Response.CacheControl = "no-cache";
        Response.AppendHeader("Pragma", "No-Cache"); 

        JavaScriptSerializer json = new JavaScriptSerializer();
        if (!String.IsNullOrEmpty(Request.QueryString["Action"]))
        {
            string action = BadChar.ReplaceBadChar(Request.QueryString["Action"]);
            switch (action)
            {
                #region changePassword修改登录密码
                case "changePassword":
                    {
                        Result<School> result = new Result<School>();
                        try
                        {
                            if (!SchoolAdmin.IsSchoolSessionValid())
                                throw new Exception("您的登录已超时，请重新登录！");
                            School school = (School)Session["school"];
                            string oldPassword = Request.Form["oldPassword"].Trim();
                            string newPassword = Request.Form["newPassword"].Trim();
                            string confirmPassword = Request.Form["confirmPassword"].Trim();
                            if (String.IsNullOrEmpty(newPassword))
                                throw new Exception("新密码不能为空");
                            if (!newPassword.Equals(confirmPassword))
                                throw new Exception("两次密码不一致");
                            SchoolAdmin.ChangePassword(school.schoolId, Tools.MD5Encrypt(oldPassword), Tools.MD5Encrypt(newPassword));
                            result.error = false;
                            result.msg = "修改登录密码成功";
                        }
                        catch (Exception ex)
                        {
                            result.error = true;
                            result.msg = ex.Message;
                        }
                        Response.Write(json.Serialize(result));
                    }
                    break;
                #endregion
                #region updateSchool更新学校信息
                case "updateSchool":
                    {
                        Result<School> result = new Result<School>();
                        try
                        {
                            if (!SchoolAdmin.IsSchoolSessionValid())
                                throw new Exception("您的登录已超时，请重新登录！");
                            School school = (School)Session["school"];
                            string schoolName = Request.Form["schoolName"].Trim();
                            string legalRepresentative = Request.Form["legalRepresentative"].Trim();
                            string telnumber = Request.Form["telnumber"].Trim();
                            SchoolAdmin.UpdateSchool(school.schoolId, schoolName, legalRepresentative, telnumber);
                            school.schoolName = schoolName;
                            school.legalRepresentative = legalRepresentative;
                            school.telnumber = telnumber;
                            Session["school"] = school;
                            result.error = false;
                            result.msg = "修改学校基本信息成功";
                        }
                        catch (Exception ex)
                        {
                            result.error = true;
                            result.msg = ex.Message;
                        }
                        Response.Write(json.Serialize(result));
                    }
                    break;
                #endregion
                #region checkLogin验证登录
                case "checkLogin":
                    {
                        Result<School> result = new Result<School>();
                        try
                        {
                            string loginId = Request.Form["loginId"].Trim();
                            string loginPass = Request.Form["loginPass"].Trim();
                            string safeCode = Request.Form["safeCode"].Trim().ToUpper();
                            if (Session["SafeCode"] == null)
                                throw new Exception("验证码超时！");
                            if (!safeCode.Equals((string)Session["SafeCode"]))
                            {
                                Session["SafeCode"] = null;
                                throw new Exception("验证码错误！");
                            }
                            if(loginId.Equals("")||loginPass.Equals(""))
                                throw new Exception("登录ID，密码均不能为空！");
                            loginId = BadChar.ReplaceBadChar(loginId);
                            loginPass = BadChar.ReplaceBadChar(loginPass);
                            School school = SchoolAdmin.CheckLogin(loginId, Tools.MD5Encrypt(loginPass));
                            if (school.loginTimes == 1)
                                SchoolAdmin.CreateSchoolBySystem(school.schoolId);
                            Session["school"] = school;
                            Session.Timeout = 25;
                            result.error = false;
                            result.msg = "登录成功";
                        }
                        catch (Exception ex)
                        {
                            result.error = true;
                            result.msg = ex.Message;
                        }
                        Response.Write(json.Serialize(result));
                    }
                    break;
                #endregion
                #region updateStatus更新状态
                case "updateStatus":
                    {
                        Result<object> result = new Result<object>();
                        try
                        {
                            if (!Tools.IsAdminSessionValid() || !RoleAdmin.CheckRole("学校管理", (Basic.VO.Admin)Session["admin"]))
                                throw new Exception("你没有这个权限");
                            int schoolId = int.Parse(Request.QueryString["schoolId"]);
                            int status = int.Parse(Request.QueryString["status"]);
                            SchoolAdmin.UpdateSchoolStatus(schoolId, status);
                            result.error = false;
                            if (status != 1)
                                result.msg = "修改学校状态成功";
                            else
                                result.msg = "删除学校成功";
                        }
                        catch (Exception ex)
                        {
                            result.error = true;
                            result.msg = ex.Message;
                        }
                        Response.Write(json.Serialize(result));
                    }
                    break;
                #endregion
                #region search查询列表
                case "search":
                    {
                        Result<School> result = new Result<School>();
                        try
                        {
                            if (!Tools.IsAdminSessionValid() || !RoleAdmin.CheckRole("学校管理", (Basic.VO.Admin)Session["admin"]))
                                throw new Exception("你没有这个权限");
                            string schoolName = String.Empty, loginId = String.Empty;
                            if (!String.IsNullOrEmpty(Request.QueryString["schoolName"]))
                                schoolName = BadChar.ReplaceBadChar(Request.QueryString["schoolName"].Trim());
                            if (!String.IsNullOrEmpty(Request.QueryString["loginId"]))
                                loginId = BadChar.ReplaceBadChar(Request.QueryString["loginId"].Trim());
                            int page = int.Parse(Request["page"]);
                            int perPage = int.Parse(Request["perpage"]);
                            PageResult<School> pageResult = SchoolAdmin.GetsSchool(schoolName, loginId, (page - 1) * perPage, page * perPage);
                            result.data = pageResult.data;
                            result.total = pageResult.totalCount;
                            result.page = page;
                            result.error = false;
                            result.msg = "查询学校列表成功";
                        }
                        catch (Exception ex)
                        {
                            result.error = true;
                            result.msg = ex.Message;
                        }
                        Response.Write(json.Serialize(result));
                    }
                    break;
                #endregion
                #region saveSchoolRegister保存学校注册信息
                case "saveSchoolRegister":
                    {
                        Result<object> result = new Result<object>();
                        try
                        {
                            int typeId = int.Parse(Request.Form["schoolType"]);
                            string schoolName = Request.Form["schoolName"].Trim();
                            string legalRepresentative = Request.Form["legalRepresentative"].Trim();
                            string telnumber = Request.Form["telnumber"].Trim();
                            string loginId = Request.Form["loginId"].Trim();
                            string loginPass = Request.Form["loginPass"].Trim();
                            string loginPassConfirm = Request.Form["loginPassConfirm"].Trim();
                            string safeCode = Request.Form["safeCode"].ToUpper();
                            if (BadChar.IsBadChar(schoolName) || BadChar.IsBadChar(legalRepresentative) || BadChar.IsBadChar(loginId) || BadChar.IsBadChar(telnumber))
                                throw new Exception("提交的数据中包含非法字符，非法字符为（|隔开）：" + BadChar.badCharString);
                            if (!loginPass.Equals(loginPassConfirm))
                                throw new Exception("两次密码不一致");
                            if (Session["SafeCode"] == null)
                                throw new Exception("验证码超时！");
                            if (!safeCode.Equals((string)Session["SafeCode"]))
                            {
                                Session["SafeCode"] = null;
                                throw new Exception("验证码错误");
                            }
                            Session["SafeCode"] = null;
                            SchoolAdmin.AddSchool(typeId,schoolName,legalRepresentative,telnumber,loginId,Tools.MD5Encrypt(loginPass));
                            result.error = false;
                            result.msg = "成功提交申请，请等待审核通过。";
                        }
                        catch (Exception ex)
                        {
                            result.error = true;
                            result.msg = ex.Message;
                        }
                        Response.Write(json.Serialize(result));
                    }
                    break;
                #endregion
                default:
                    {
                        Result<object> result = new Result<object>();
                        result.error = true;
                        result.msg = StringTable.ErrorUnknowAction;
                        Response.Write(json.Serialize(result));
                    }
                    break;
            }
        }
        else
        {
            Result<object> result = new Result<object>();
            result.error = true;
            result.msg = StringTable.ErrorMissingParameters;
            Response.Write(json.Serialize(result));
        }
        Response.End();
    }
}
